package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckillController")
public class SeckillController {

    @Reference(timeout = 60000)
    private SeckillService seckillService;

    @RequestMapping("toSeckillList")
    public String toSeckillList(Model model){
        List<TbSeckillGoods> seckillGoodsList = seckillService.selectSeckill();
        model.addAttribute("list",seckillGoodsList);
        return "seckill-index";
    }

    @RequestMapping("findGoodsById/{id}")
    public String findGoodsById(@PathVariable("id") Long id, Model model){
        TbSeckillGoods  seckillGoods =seckillService.findGoodsById(id);
        if (seckillGoods == null){
            return "saleOver";
        }
        model.addAttribute("seckillGoods",seckillGoods);
        return "seckill-item";
    }

    @RequestMapping("buying")
    @ResponseBody
    public Result buying(Long id){
        //下单.然后跳转支付
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.NOLOGIN);
        }
        try{
            seckillService.createOrder(id,user.getUsername());
        }catch (Exception e){
            return Result.response(ResultEnum.SALE_OVER);
        }

        return Result.response(ResultEnum.SUCCESS);
    }

    @RequestMapping("getOrderId")
    @ResponseBody
    public Result getOrderId(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        Long orderId = seckillService.getOrderId(user.getUsername());
        return Result.response(ResultEnum.SUCCESS).setData(orderId);
    }



}
